﻿using SlamDunk.CMS.Model.DataModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using SD.Common.PoweredByLee;

namespace SlamDunk.CMS.DAL
{
    public class MasterScoreLineDal
    {
        #region # 静态构造器

        /// <summary>
        /// SqlHelper
        /// </summary>
        private static readonly SqlHelper _SqlHelper;

        /// <summary>
        /// 静态构造器
        /// </summary>
        static MasterScoreLineDal()
        {
            _SqlHelper = new SqlHelper(ConfigurationManager.ConnectionStrings["CMS"].ConnectionString);
        }

        #endregion

        #region 01.根据年份与类别条件获取记录条数
        /// <summary>
        /// 根据年份与类别条件获取记录条数
        /// </summary>
        /// <param name="year">年份</param>
        /// <param name="category">类别</param>
        /// <returns>记录条数</returns>
        public int GetCount(int year, int category)
        {
            string sql = "SELECT COUNT(*) FROM dbo.MasterScoreLines WHERE 0 = 0";

            #region 非空校验
            if (year != 0)
            {
                sql = string.Format("{0} AND [Year] = {1}", sql, year);
            }
            if (category != 0)
            {
                sql = string.Format("{0} AND Category = {1}", sql, category);
            }
            #endregion

            return (int)_SqlHelper.ExecuteScalar(sql);
        }
        #endregion

        #region 02.根据年份与类别条件获取获取实体对象集合
        /// <summary>
        /// 根据年份与类别条件获取获取实体对象集合
        /// </summary>
        /// <param name="start">起始行</param>
        /// <param name="end">终止行</param>
        /// <param name="year">年份</param>
        /// <param name="category">类别</param>
        /// <returns>实体对象集合</returns>
        public List<MasterScoreLine> GetModelList(int start, int end, int year, int category)
        {
            List<MasterScoreLine> list = new List<MasterScoreLine>();
            string sql = "SELECT *, ROW_NUMBER() OVER(ORDER BY [Year] DESC, Category ASC) AS RowIndex FROM dbo.MasterScoreLines WHERE 0 = 0";

            #region 非空校验
            if (year != 0)
            {
                sql = string.Format("{0} AND [Year] = {1}", sql, year);
            }
            if (category != 0)
            {
                sql = string.Format("{0} AND Category = {1}", sql, category);
            }
            #endregion

            //分页处理
            sql = string.Format("SELECT * FROM ({0}) AS T WHERE T.RowIndex >= @Start AND T.RowIndex <= @End", sql);

            SqlParameter[] args = new SqlParameter[] {
                new SqlParameter("@Start", start),
                new SqlParameter("@End", end)
            };

            using (SqlDataReader reader = _SqlHelper.ExecuteReader(sql, args))
            {
                while (reader.Read())
                {
                    list.Add(this.ToModel(reader));
                }
            }
            return list;
        }
        #endregion

        #region 03.获取所有年份
        /// <summary>
        /// 获取所有年份
        /// </summary>
        /// <returns>年份集合</returns>
        public List<int> GetAllYear()
        {
            List<int> list = new List<int>();

            string sql = "SELECT DISTINCT [Year] FROM dbo.MasterScoreLines ORDER BY [Year] DESC";
            using (SqlDataReader reader = _SqlHelper.ExecuteReader(sql))
            {
                while (reader.Read())
                {
                    list.Add((int)(reader as SqlDataReader)[0]);
                }
            }
            return list;
        }
        #endregion

        #region 01.添加方法
        /// <summary>
        /// 添加一个实体对象
        /// </summary>
        /// <param name="masterScoreLine">要添加的实体对象</param>
        /// <returns>添加完毕后的实体对象</returns>
        public MasterScoreLine Add(MasterScoreLine masterScoreLine)
        {
            string sql = "INSERT INTO MasterScoreLines (Province, Year, Major, Category, SumScore, PoliticsEnglish, BusiCompre, AdmitCount, DelFlag, AddTime)  output inserted.Id VALUES (@Province, @Year, @Major, @Category, @SumScore, @PoliticsEnglish, @BusiCompre, @AdmitCount, @DelFlag, @AddTime)";
            SqlParameter[] args = new SqlParameter[] {
                new SqlParameter("@Province", ToDBValue(masterScoreLine.Province)),
                new SqlParameter("@Year", ToDBValue(masterScoreLine.Year)),
                new SqlParameter("@Major", ToDBValue(masterScoreLine.Major)),
                new SqlParameter("@Category", ToDBValue(masterScoreLine.Category)),
                new SqlParameter("@SumScore", ToDBValue(masterScoreLine.SumScore)),
                new SqlParameter("@PoliticsEnglish", ToDBValue(masterScoreLine.PoliticsEnglish)),
                new SqlParameter("@BusiCompre", ToDBValue(masterScoreLine.BusiCompre)),
                new SqlParameter("@AdmitCount", ToDBValue(masterScoreLine.AdmitCount)),
                new SqlParameter("@DelFlag", ToDBValue(masterScoreLine.DelFlag)),
                new SqlParameter("@AddTime", ToDBValue(masterScoreLine.AddTime)),
            };
            //根据newId返回新添加的实体对象
            int newId = (int)_SqlHelper.ExecuteScalar(sql, args);
            return this.GetModel(newId);
        }
        #endregion

        #region 02.删除方法（物理删除）
        /// <summary>
        /// 删除一个实体对象
        /// </summary>
        /// <param name="id">要删除的实体对象Id</param>
        /// <returns>受影响的行数</returns>
        public int PhysicalDelete(int id)
        {
            string sql = "DELETE FROM MasterScoreLines WHERE Id = @Id";
            SqlParameter arg = new SqlParameter("@Id", id);
            return _SqlHelper.ExecuteNonQuery(sql, arg);
        }
        #endregion

        #region 04.修改方法
        /// <summary>
        /// 修改一个实体对象
        /// </summary>
        /// <param name="masterScoreLine">构造好的要修改的实体对象</param>
        /// <returns>受影响的行数</returns>
        public int Update(MasterScoreLine masterScoreLine)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("UPDATE MasterScoreLines SET Province = @Province");
            sql.Append(", Year = @Year");
            sql.Append(", Major = @Major");
            sql.Append(", Category = @Category");
            sql.Append(", SumScore = @SumScore");
            sql.Append(", PoliticsEnglish = @PoliticsEnglish");
            sql.Append(", BusiCompre = @BusiCompre");
            sql.Append(", AdmitCount = @AdmitCount");
            sql.Append(", DelFlag = @DelFlag");
            sql.Append(", AddTime = @AddTime");
            sql.Append(" WHERE Id = @Id");
            SqlParameter[] args = new SqlParameter[] {
                new SqlParameter("@Id", masterScoreLine.Id)
                ,new SqlParameter("@Province", ToDBValue(masterScoreLine.Province))
                ,new SqlParameter("@Year", ToDBValue(masterScoreLine.Year))
                ,new SqlParameter("@Major", ToDBValue(masterScoreLine.Major))
                ,new SqlParameter("@Category", ToDBValue(masterScoreLine.Category))
                ,new SqlParameter("@SumScore", ToDBValue(masterScoreLine.SumScore))
                ,new SqlParameter("@PoliticsEnglish", ToDBValue(masterScoreLine.PoliticsEnglish))
                ,new SqlParameter("@BusiCompre", ToDBValue(masterScoreLine.BusiCompre))
                ,new SqlParameter("@AdmitCount", ToDBValue(masterScoreLine.AdmitCount))
                ,new SqlParameter("@DelFlag", ToDBValue(masterScoreLine.DelFlag))
                ,new SqlParameter("@AddTime", ToDBValue(masterScoreLine.AddTime))
            };
            return _SqlHelper.ExecuteNonQuery(sql.ToString(), args);
        }
        #endregion

        #region 05.根据主键获取单个实体对象
        /// <summary>
        /// 根据主键获取单个实体对象
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>单个实体对象</returns>
        public MasterScoreLine GetModel(int id)
        {
            string sql = "SELECT * FROM MasterScoreLines WHERE Id = @Id";
            using (SqlDataReader reader = _SqlHelper.ExecuteReader(sql, new SqlParameter("@Id", id)))
            {
                if (reader.Read())
                {
                    return ToModel(reader);
                }
                else
                {
                    return null;
                }
            }
        }
        #endregion

        #region 17.根据IDataReader对象返回实体对象方法
        /// <summary>
        /// 根据IDataReader对象返回实体对象方法
        /// </summary>
        /// <param name="reader">IDataReader对象</param>
        /// <returns>实体对象</returns>
        public MasterScoreLine ToModel(IDataReader reader)
        {
            MasterScoreLine masterScoreLine = new MasterScoreLine();
            masterScoreLine.Id = (int)ToModelValue(reader as SqlDataReader, "Id");
            masterScoreLine.Province = (string)ToModelValue(reader as SqlDataReader, "Province");
            masterScoreLine.Year = (int)ToModelValue(reader as SqlDataReader, "Year");
            masterScoreLine.Major = (string)ToModelValue(reader as SqlDataReader, "Major");
            masterScoreLine.Category = (int)ToModelValue(reader as SqlDataReader, "Category");
            masterScoreLine.SumScore = (int)ToModelValue(reader as SqlDataReader, "SumScore");
            masterScoreLine.PoliticsEnglish = (int)ToModelValue(reader as SqlDataReader, "PoliticsEnglish");
            masterScoreLine.BusiCompre = (int)ToModelValue(reader as SqlDataReader, "BusiCompre");
            masterScoreLine.AdmitCount = (int?)ToModelValue(reader as SqlDataReader, "AdmitCount");
            masterScoreLine.DelFlag = (bool)ToModelValue(reader as SqlDataReader, "DelFlag");
            masterScoreLine.AddTime = (DateTime)ToModelValue(reader as SqlDataReader, "AddTime");
            return masterScoreLine;
        }
        #endregion

        #region 18.C#值转数据库值空值处理
        /// <summary>
        /// C#值转数据库值空值处理
        /// </summary>
        /// <param name="value">C#值</param>
        /// <returns>处理后的数据库值</returns>
        public object ToDBValue(object value)
        {
            if (value == null)
            {
                return DBNull.Value;
            }
            else
            {
                return value;
            }
        }
        #endregion

        #region 19.数据库值转C#值空值处理
        /// <summary>
        /// 数据库值转C#值空值处理
        /// </summary>
        /// <param name="reader">IDataReader对象</param>
        /// <param name="columnName">列名</param>
        /// <returns>C#值</returns>
        public object ToModelValue(IDataReader reader, string columnName)
        {
            if (reader.IsDBNull(reader.GetOrdinal(columnName)))
            {
                return null;
            }
            else
            {
                return reader[columnName];
            }
        }
        #endregion
    }
}
